/*
    两组串口
    PA9 PA10
    PA2 PA3
*/

#include "stm32f10x_conf.h"

#include <string.h>
#include <stdio.h>
#include <stdint.h>

#include "hal.h"

static uart_retrive_ch uart1_cb = NULL;

void uart1_init(void)
{
    GPIO_InitTypeDef GPIO_InitStructure;
    USART_InitTypeDef USART_InitStructure;
    NVIC_InitTypeDef NVIC_InitStructure;

    RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1|
    RCC_APB2Periph_GPIOA, ENABLE);  
    
    USART_DeInit(USART1);     
    
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;  
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;      
    GPIO_Init(GPIOA, &GPIO_InitStructure);    
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;  
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;                  
    GPIO_Init(GPIOA, &GPIO_InitStructure);   

    USART_InitStructure.USART_BaudRate = 115200;      
    USART_InitStructure.USART_WordLength =     USART_WordLength_8b; 
    USART_InitStructure.USART_StopBits = USART_StopBits_1;  
    USART_InitStructure.USART_Parity = USART_Parity_No;  
    USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;  
    USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
    USART_Init(USART1, &USART_InitStructure);   

    NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=3 ; 
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;      
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;      
    NVIC_Init(&NVIC_InitStructure);        
    USART_ITConfig(USART1, USART_IT_RXNE, ENABLE); 

    USART_Cmd(USART1, ENABLE);     
}

void uart1_init_cb(uart_retrive_ch cb)
{
    uart1_init();
    uart1_cb = cb;
}

void uart1_byte(uint8_t ch)
{
    USART_SendData(USART1, ch);
    while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
}

void uart1_send_string(char *s)
{
    size_t len,i;
    
    len = strlen(s);
    
    for(i = 0;i < len;i++)
        uart1_byte(s[i]);
}

// 串口1 接收中断服务程序
void USART1_IRQHandler(void)
{
    uint8_t ch;
    
    if( USART_GetITStatus(USART1,USART_IT_RXNE) )
    {
        USART_ClearITPendingBit(USART1,USART_IT_RXNE);   
        ch = USART_ReceiveData(USART1);

        if(NULL != uart1_cb)
            (*uart1_cb)(ch);
    }
}


// end of file -------------------

